# -*-coding: utf-8 -*-
# by zw on 2017/12/25

import logging

from sanic import Sanic
from sanic import response
from sanic_jinja2 import SanicJinja2
from sanic_session import RedisSessionInterface

from settings import config
from utils.mongo import init_db, close_db
from utils.asyncio_redis import redis
from utils.aio_redis_pool import AioRedisPool

app = Sanic(log_config=config['logging'])

_logger = logging.getLogger()
_oplog = logging.getLogger("oplog")

jinja = SanicJinja2(app)
jinja.env.variable_start_string = "<{"
jinja.env.variable_end_string = "}>"
jinja.env.comment_start_string = "<#"
jinja.env.comment_end_string = "#>"



# pass the getter method for the connection pool into the session
session = RedisSessionInterface(redis.get_redis_pool)


@app.middleware('request')
async def add_session_to_request(request):
    # before each request initialize a session
    # using the client's request
    await session.open(request)


@app.middleware('response')
async def save_session(request, response):
    # after each request save the session,
    # pass the response to set client cookies
    await session.save(request, response)


@app.middleware('request')
async def log_on_request(request):
    user = request.cookies.get('user')
    host = request.host

    # _oplog.info("user: %s, host: %s args: %s, json: %s" % (user, host, request.raw_args, request.json))


@app.listener("before_server_start")
async def before_server_start(app, loop):
    init_db()
    _logger.info("init db ok and reset redis pool")
    AioRedisPool.reset_pool()


@app.listener("after_server_stop")
async def after_server_stop(app, loop):
    close_db()
    _logger.info("close db ")
    _logger.info("close redis pool ")
    await AioRedisPool.close_pool()


async def home(request):
    try:
        return response.redirect("/admin/index2.html")
    except Exception as e:
        _logger.exception("url %s exception %s" % (request.url, e))
        return response.json({"code": 4003, "message": "error message %s" % e, "data": {}})
